import { promises as fs } from "fs";
import path from "path";
import matter from "gray-matter";
import { unified } from "unified";
import remarkParse from "remark-parse";
import { visit } from "unist-util-visit";
import rehypeSlug from "rehype-slug";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeKatex from "rehype-katex";
import rehypeAddClasses from "rehype-add-classes";
import GithubSlugger from "github-slugger";

import "highlight.js/styles/github.css";


import { serialize } from "next-mdx-remote/serialize";

// 注意: 不再使用 serialize，而使用 compileMDX 来生成渲染用的 MDX 源 } from 'next-mdx-remote/rsc';

const docsDir = path.join(process.cwd(), "docs");

export async function getAllDocs() {
    const files = await fs.readdir(docsDir);
    return Promise.all(
        files
            .filter((f) => f.endsWith(".md"))
            .map(async (file) => {
                const slug = file.replace(/\.md$/, "");
                const full = path.join(docsDir, file);
                const content = await fs.readFile(full, "utf-8");
                const { data } = matter(content);
                return { slug, title: data.title || slug };
            })
    );
}

export async function getDocBySlug(slug: any) {
    const fullPath = path.join(docsDir, `${slug}.md`);
    const raw = await fs.readFile(fullPath, "utf-8");
    const { data: frontMatter, content } = matter(raw);
    // 提取 H2/H3 标题
    const ast = unified().use(remarkParse).use(remarkRehype).parse(content);

    const slugger = new GithubSlugger();


    const headings: any = [];
    visit(ast, "heading", (node) => {
        if (node.depth === 2 || node.depth === 3) {
            const text = node.children
                .filter((c) => c.type === "text")
                .map((c) => c.value)
                .join("");
            const id = slugger.slug(text);
            headings.push({ text, level: node.depth, id });
        }
    });

    const serialized = await serialize(content, {
        mdxOptions: {
            remarkPlugins: [remarkGfm],
            rehypePlugins: [
                rehypeSlug,
                [rehypeAutolinkHeadings, { behavior: "wrap" }],
                rehypeHighlight,
                [rehypeKatex, { strict: true, throwOnError: true }],
                [
                    rehypeAddClasses,
                    {
                        h1: "text-3xl font-bold mb-4",
                        h2: "text-2xl font-semibold mb-3",
                        h3: "text-1xl font-semibold mb-3",
                        p: "my-2 leading-relaxed",
                        pre: "my-4 p-4 bg-gray-100 rounded",
                        code: "text-sm",
                    },
                ],
            ],
        },
    });


    return { frontMatter, mdxSource: serialized, headings };
}
